package cj.web.admin.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.web.admin.constants.Constants;
import cj.web.admin.dao.RoleInfoDAO;
import cj.web.admin.dao.UserInfoDAO;
import cj.web.admin.dao.UserRoleRefDAO;
import cj.web.admin.domain.RoleInfo;
import cj.web.admin.domain.UserInfo;
import cj.web.admin.domain.UserRoleRef;
import cj.web.admin.utils.Base64;
import cj.web.admin.utils.MD5Security;
import cj.web.login.controllers.BaseController;

@Path("/userinfo")
public class UserController extends BaseController{

	private static Logger logger = Logger.getLogger(UserController.class.getName());
	
	@Autowired
	private UserInfoDAO userInfoDao;
	@Autowired
	private RoleInfoDAO roleInfoDao;
	@Autowired
	private UserRoleRefDAO userRoleRefDao;
	
	@Get("show")
	public String show(Model model)
	{
		return "/views/user/userInfoList.vm";
	}

	@Post("getList")
	public String getUserList(UserInfo userInfo) {
		//当前页  
        userInfo.setStart((userInfo.getPage()-1)*userInfo.getRows());
		userInfo.setLength(userInfo.getRows());
		
		JSONObject jo = new JSONObject();
		
		List<Map> objs = userInfoDao.query(userInfo);
		
		int size = userInfoDao.querysize(userInfo);
		jo.put("rows", objs);
		jo.put("total", size);
		return "@"+jo.toString();
	}
	
	@Get("createPage")
	public String createPage(Model model)
	{
		return "/views/user/userInfoDetail.vm";
	}
	
	@Post("create")
	public String create(Model model,UserInfo userInfo,HttpServletRequest request,@Param("roleId") String roleId)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);

		int size = userInfoDao.queryByAccount(userInfo.getAccount());
		
		if(size>0)
		{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("code", Constants.returnObj.returnCode.code_1);
			return "@"+jo.toString();
		}
		
		try {
			String pwd = userInfo.getPwd();
			userInfo.setPwd(MD5Security.md5(pwd));
			userInfo.setPhoto(Base64.getBase64(pwd));
			userInfo.setCreateUser(returnSessionObj(request).getAccount());
			userInfo.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
			userInfo.setUpdateUser(returnSessionObj(request).getAccount());
			userInfo.setType(Constants.portal.userState.state_1);
			userInfo.setState(Constants.portal.userState.state_1);
			int id = userInfoDao.create(userInfo);
			
			if(roleId!=null && !"".equals(roleId))
				//角色ID
			{
				for(String rid:roleId.split(","))
				{
					UserRoleRef obj = new UserRoleRef();
					obj.setUserId(id);
					obj.setRoleId(Integer.parseInt(rid));
					userRoleRefDao.create(obj);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	/**
	 * 个人编辑方法
	 * @param model
	 * @param userInfo
	 * @param request
	 * @param roleId
	 * @return
	 */
	@Post("perUpdate")
	public String perUpdate(Model model,@Param("pwd") String pwd,HttpServletRequest request)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			UserInfo l_userInfo = userInfoDao.queryById(returnSessionObj(request).getId());
			
			l_userInfo.setPwd(MD5Security.md5(pwd));
			l_userInfo.setPhoto(Base64.getBase64(pwd));
			l_userInfo.setUpdateUser(returnSessionObj(request).getAccount());
			userInfoDao.update(l_userInfo);
			
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("edit")
	public String edit(Model model,@Param("id") int id)
	{
		UserInfo obj = userInfoDao.queryById(id);
		
		obj.setPwd(Base64.getFromBase64(obj.getPhoto()));
		
		List<UserRoleRef> userRoleRefs = userRoleRefDao.queryId(id);
		
		String roleId = "";
		
		for(UserRoleRef urp:userRoleRefs)
		{
			roleId+=urp.getRoleId()+",";
		}
		
		model.add("roleId", roleId);
		model.add("userinfo", obj);
		return "/views/user/userInfoEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,UserInfo userInfo,HttpServletRequest request,@Param("roleId") String roleId)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			String pwd = userInfo.getPwd();
			userInfo.setPwd(MD5Security.md5(pwd));
			userInfo.setPhoto(Base64.getBase64(pwd));
			userInfo.setUpdateUser(returnSessionObj(request).getAccount());
			userInfoDao.update(userInfo);
			
			if(roleId!=null && !"".equals(roleId))
				//角色ID
			{
				userRoleRefDao.deleteById(userInfo.getId());
				for(String rid:roleId.split(","))
				{
					UserRoleRef obj = new UserRoleRef();
					obj.setUserId(userInfo.getId());
					obj.setRoleId(Integer.parseInt(rid));
					userRoleRefDao.create(obj);
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("Ids") String Ids)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(","))
		{
			userInfoDao.deleteById(Integer.parseInt(id));
		}
		
		return "@"+jo.toString();
	}
	
	@Get("userRefRoleJson")
	public String userRefRoleJson(@Param("roleId") String roleId)
	{
		JSONObject jo = new JSONObject();
		List<RoleInfo> roleInfos = roleInfoDao.getListAll();
		List<Map> reps = new ArrayList<Map>();
		for(RoleInfo obj:roleInfos)
		{
			Map rep = new HashMap();
			rep.put("id", obj.getId());
			rep.put("pId", 0);
			rep.put("name", obj.getName());
			rep.put("open", true);
			if(roleId!=null)
			{
				rep.put("checked", (","+roleId).indexOf(","+obj.getId()+",")!=-1?true:false);
			}
			else
			{
				rep.put("checked", false);
			}
			
			reps.add(rep);
		}
		jo.put("reps", reps);
		return "@"+jo.toString();
	}
}
